package com.leetao.dingtalk.core.domain.rest;


/**
 * 后端统一返回结果
 * @author 菅江晖
 * @date 2021/4/27 - 9:45
 */
public class Rest<T> {

    private final static int SUCCESS = 0;
    private final static int ERROR = -1;

    private final static String SUCCESS_MSG = "成功";
    private final static String ERROR_MSG = "失败";

    /**
     * 错误码
     */
    int code;

    /**
     * 消息
     */
    String msg;

    /**
     * 数据
     */
    T data;

    public int getCode() {
        return code;
    }

    public String getMsg() {
        return msg;
    }

    public T getData() {
        return data;
    }

    private static <T> Rest<T> create(int code, String msg, T data) {
        return new Rest<T>(code, msg, data);
    }


    public static <T> Rest<T> success(String msg, T data) {
        return create(SUCCESS, msg, data);
    }

    public static <T> Rest<T> success(String msg) {
        return create(SUCCESS, msg, null);
    }

    public static <T> Rest<T> success(T data) {
        return create(SUCCESS, SUCCESS_MSG, data);
    }

    public static <T> Rest<T> success() {
        return create(SUCCESS, SUCCESS_MSG, null);
    }


    public static <T> Rest<T> error(int code, String msg, T data) {
        return create(code, msg, data);
    }

    public static <T> Rest<T> error(ResultEnum resultEnum, T data) {
        return create(resultEnum.code(), resultEnum.msg(), data);
    }

    public static <T> Rest<T> error(ResultEnum resultEnum) {
        return create(resultEnum.code(), resultEnum.msg(), null);
    }

    public static <T> Rest<T> error(int code,String msg) {
        return create(code, msg, null);
    }

    public static <T> Rest<T> error(String msg, T data) {
        return create(ERROR, msg, data);
    }

    public static <T> Rest<T> error(String msg) {
        return create(ERROR, msg, null);
    }

    public static <T> Rest<T> error(T data) {
        return create(ERROR, ERROR_MSG, data);
    }

    public static <T> Rest<T> error() {
        return create(ERROR, ERROR_MSG, null);
    }


    private Rest(int code, String msg, T data) {
        this.code = code;
        this.msg = msg;
        this.data = data;
    }

    @Override
    public String toString() {
        final StringBuilder sb = new StringBuilder("Rest{");
        sb.append("code=").append(code);
        sb.append(", msg='").append(msg).append('\'');
        sb.append(", data=").append(data);
        sb.append('}');
        return sb.toString();
    }
}
